package pri.hillchen.std.concurrent.chapter5;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

/**
 * Created by hillchen on 2018/2/8.
 */
public class LifecycleWebServer {
    private final ExecutorService executorService ;

    public LifecycleWebServer(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public void start() throws IOException {
        ServerSocket serverSocket = new ServerSocket(80);
        if(!executorService.isShutdown()){
            final Socket socket = serverSocket.accept();
            executorService.execute(new RequestHandler(socket));
        }
    }

    class RequestHandler implements Runnable{
        private final Socket socket;

        public RequestHandler(Socket socket) {
            this.socket = socket;
        }

        public void handleRequest() throws IOException {
            /**handle socket**/
            socket.getOutputStream();
            socket.close();
        }

        public void run() {
            try {
                handleRequest();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
